package com.ttg.utils;

/**
 * Class IdGenerator
 * Description 订单号生成
 * Create 2015-09-12 15:11:26
 * @author Ardy
 */
public class IdGenerator {

    /**
     * Field SYS_CONFIG
     * Description
     */
    private static final String SYS_CONFIG = "config";

    /**
     * Field i
     * Description 订单号（生成规则：取系统配置文件的instance号2位+12位currentTimeMillis/10(10毫秒)+2位流水号）
     */
    private static int i = 0;

    /**
     * Field instanceId
     * Description
     */
    private static String instanceId ="01";

    /**
     * Method getInstanceId
     * Description
     *
     * @return String
     */
    public static String getInstanceId() {
        return instanceId;
    }

    /**
     * Method setInstanceId
     * Description
     *
     * @param instanceId String
     */
    public static void setInstanceId(String instanceId) {
        if (( instanceId == null ) || ( instanceId.length() != 2 )) {
            throw new IllegalArgumentException("Set instanceId error: the length should be 2 '"
                                               + ( ( instanceId == null ) ? "" : instanceId ) + "' is not correct.");
        }

        IdGenerator.instanceId = instanceId;
    }

    /**
     * Method genOrdId16
     * Description 每10毫秒可生成100个序列号；优于每毫秒10个序列号
     *
     * @return String
     */
    public synchronized static String genOrdId16() {
        i = i % 100;

        String index    = ( i < 10 ) ? ( "0" + i ) : "" + i;
        String orderNum = instanceId + System.currentTimeMillis() / 10 + index;

        i++;

        return orderNum;
    }

    /**
     * Method main
     * Description
     *
     * @param args String[]
     */
    public static void main(String[] args) {
        for (int i = 0 ; i < 100 ; i++) {
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    System.err.println(genOrdId16());
                }
            });

            t.start();
        }
    }
}


//~ Formatted by Jindent --- http://www.jindent.com
